//
//  WFFarmEditViewController.m
//  WisdomFarm
//
//  Created by 心情 on 2017/10/26.
//  Copyright © 2017年 sky. All rights reserved.
//

#import "WFFarmEditViewController.h"
#import "WFFarmRequest.h"
#import "WFTextFieldTableViewCell.h"
#import "WFFarmLocationCell.h"
#import "WFFarmCropHeaderView.h"
#import "WFFarmCropCell.h"
#import "WFSeparatorTableViewCell.h"
#import "WFButtonTableFooterView.h"
#import "UITableViewCell+WFHeight.h"
#import "WFButtonCell.h"
#import "UIAlertController+WF.h"
#import "WFAddCropViewController.h"
#import "WFFarmDao.h"

@interface WFFarmEditViewController ()<
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) WFFarm *farm;
@property (nonatomic, strong) WFFarm *modifiedFarm;

@property (nonatomic, strong) NSArray<UITableViewCell *> *cells;
@property (nonatomic, strong) WFTextFieldTableViewCell *nameCell;
@property (nonatomic, strong) WFSeparatorTableViewCell *nameSeparatorCell;
@property (nonatomic, strong) WFFarmLocationCell *locationCell;
@property (nonatomic, strong) WFSeparatorTableViewCell *locationSeparatorCell;

@property (nonatomic, strong) WFFarmCropHeaderView *cropHeaderView;
@property (nonatomic, strong) WFButtonCell *addCropCell;

@property (nonatomic, strong) WFButtonTableFooterView *footerView;


@end

@implementation WFFarmEditViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.title = self.farmId ? @"编辑农场" : @"新增农场";

    self.nameCell = [[WFTextFieldTableViewCell alloc] init];
    self.nameCell.cellHeight = 50;
    self.nameCell.titleWidth = 73;
    self.nameCell.textLabel.text = @"农场名称";
    self.nameCell.textLabel.font = SCFont(14);
    self.nameCell.textField.text = self.farm.id ? (self.farm.name ?: @"") : @"";
    self.nameCell.separatorInset = UIEdgeInsetsMake(51, 0, 0, 0);

    self.nameSeparatorCell = [[WFSeparatorTableViewCell alloc] init];
    self.nameSeparatorCell.cellHeight = 8;
    
    self.locationCell = [[WFFarmLocationCell alloc] init];
    self.locationCell.cellHeight = 280;
    if (!self.farm.id) {
        self.locationCell.currentLocation = [WFCacheStore sharedCacheStore].currentLocation;
    }
    
    self.locationSeparatorCell = [[WFSeparatorTableViewCell alloc] init];
    self.locationSeparatorCell.cellHeight = 8;
    
    [self.tableView registerClass:[WFFarmCropCell class] forCellReuseIdentifier:@"WFFarmCropCell"];
    self.addCropCell = [[WFButtonCell alloc] init];
    [self.addCropCell.button addTarget:self action:@selector(onAddCrop) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.farmId) {
        [self requestFarmInfo];
    }
    
    [self.tableView registerClass:[WFTextFieldTableViewCell class] forCellReuseIdentifier:@"WFTextFieldTableViewCell"];
    
    self.footerView = [WFButtonTableFooterView new];
    [self.view addSubview:self.footerView];
    [self.footerView.saveButton addTarget:self action:@selector(onSave) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView.deleteButton addTarget:self action:@selector(onDelete) forControlEvents:UIControlEventTouchUpInside];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.insets(UIEdgeInsetsZero);
        make.bottom.equalTo(self.footerView.mas_top);
    }];
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.insets(UIEdgeInsetsZero);
        make.height.mas_equalTo(50);
    }];
    
    self.cells = @[
                   self.nameCell,
                   self.nameSeparatorCell,
                   self.locationCell,
                   self.locationSeparatorCell,
                   ];
    
    self.footerView.canDelete = (self.farmId.length > 0);
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (WFFarmCropHeaderView *)cropHeaderView {
    if (!_cropHeaderView) {
        _cropHeaderView = [[WFFarmCropHeaderView alloc] init];
    }
    return _cropHeaderView;
}

- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    [self.footerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.insets(UIEdgeInsetsZero);
        make.height.mas_equalTo(50 + self.view.safeAreaInsets.bottom);
    }];
}

//MARK:- request
- (void)requestFarmInfo {
    [SVProgressHUD show];
    [[WFFarmDao new] farmById:self.farmId completion:^(WFFarm *farm, NSError *error) {
        [SVProgressHUD dismiss];
        if (error) {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        self.farm = farm;
        self.modifiedFarm = [self.farm yy_modelCopy];
        self.nameCell.textField.text = self.farm.name;
        self.locationCell.currentLocation = [[CLLocation alloc] initWithLatitude:self.farm.latitude longitude:self.farm.longitude];
        [self.tableView reloadData];
    }];
    
//    WFFarmRequest *request = [WFFarmRequest new];
//    request.farmId = self.farmId;
//    [SVProgressHUD show];
//    [request startWithBlock:^(WFFarmRequest *request, NSError *error) {
//        if (error) {
//            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
//            [self.navigationController popViewControllerAnimated:YES];
//            return;
//        }
//        self.farm = request.response.resultEntity;
//        self.modifiedFarm = [self.farm yy_modelCopy];
//        [self.tableView reloadData];
//    }];
}

- (WFFarm *)modifiedFarm {
    if (!_modifiedFarm) {
        if (self.farm) {
            _modifiedFarm = [self.farm copy];
        } else {
            _modifiedFarm = [[WFFarm alloc] init];
        }
    }
    return _modifiedFarm;
}


//MARK:- tableview delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.cells[indexPath.row].cellHeight;
    } else {
        if (indexPath.row < self.modifiedFarm.crops.count) {
            return 55;
        }
    }
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return self.cells.count;
        case 1:
            return self.modifiedFarm.crops.count + 1;
        default:
            return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.cells[indexPath.row];
    }
    if (indexPath.row < self.modifiedFarm.crops.count) {
        WFFarmCropCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WFFarmCropCell" forIndexPath:indexPath];
        cell.crop = self.modifiedFarm.crops[indexPath.row];
        cell.deleteButton.tag = indexPath.row;
        [cell.deleteButton addTarget:self action:@selector(onDeleteCrop:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    } else {
        return self.addCropCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 34;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return self.cropHeaderView;
    }
    return nil;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}


//MARK:- event
- (void)onAddCrop {
    WFAddCropViewController *controller = [[WFAddCropViewController alloc] init];
    @weakify(self);
    controller.addCropFinish = ^(WFFarmCrop *crop) {
        @strongify(self);
        if (!crop) {
            return;
        }
        [self dismissViewControllerAnimated:YES completion:nil];
        NSMutableArray *crops = [self.modifiedFarm.crops mutableCopy];
        if (!crops) {
            crops = [NSMutableArray new];
        }
        [crops addObject:crop];
        self.modifiedFarm.crops = [crops copy];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
//            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
        });
    };
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)onDeleteCrop:(UIButton *)btn {
    NSInteger index = btn.tag;
    NSMutableArray *crops = [self.modifiedFarm.crops mutableCopy];
    if (crops.count > index) {
        [crops removeObjectAtIndex:index];
    }
    self.modifiedFarm.crops = [crops copy];
    [self.tableView reloadData];
}

- (void)onSave {
    self.modifiedFarm.name = self.nameCell.textField.text;
    self.modifiedFarm.latitude = self.locationCell.currentLocation.coordinate.latitude;
    self.modifiedFarm.longitude = self.locationCell.currentLocation.coordinate.longitude;
    self.modifiedFarm.address = self.locationCell.address;
    if (self.modifiedFarm.name.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入农场名称"];
        return;
    }
    if (!CLLocationCoordinate2DIsValid(self.modifiedFarm.coordinate)) {
        [SVProgressHUD showInfoWithStatus:@"请选择有效的农场位置"];
        return ;
    }
    
    WFFarmDao *farmDao = [WFFarmDao new];
    [farmDao saveFarm:self.modifiedFarm forUser:[WFStore currentUser].id completion:^(NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            return;
        }
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        if (self.farmChangedHandler) {
            self.farmChangedHandler();
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    
//    WFFarmRegisterRequest *request = [[WFFarmRegisterRequest alloc] init];
//    request.uid = [WFStore currentUser].id;
//    request.farmname = self.modifiedFarm.name;
//    request.farmlat = self.modifiedFarm.latitude;
//    request.farmlon = self.modifiedFarm.longitude;
//    request.cropIds = [self.modifiedFarm.crops cropIdComponentsJoinedByString:@","];
//    [request startWithBlock:^(__kindof MZBaseRequest *request, NSError *error) {
//        if (error) {
//            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
//            return;
//        }
//        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//        if (self.farmChangedHandler) {
//            self.farmChangedHandler();
//        } else {
//            [self.navigationController popViewControllerAnimated:YES];
//        }
//    }];
    
}

- (void)onDelete {
    @weakify(self);
    void (^handler)(NSInteger) = ^(NSInteger index) {
        @strongify(self);
        //确定
        if (index == 0) {
            if ([self.farm.uid isEqualToString:[WFStore currentUser].id]) {
                [[WFFarmDao new] deleteFarmByObjectId:self.farm.objectId completion:^(BOOL result, NSError *error) {
                    if (result) {
                        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                        if (self.farmChangedHandler) {
                            self.farmChangedHandler();
                        }
                    } else {
                        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                    }
                }];
            } else {
                [SVProgressHUD showErrorWithStatus:@"删除失败"];
            }
        }
    };
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                        message:@"确认删除该农场?"
                                                                 preferredStyle:UIAlertControllerStyleAlert
                                                                   actionTitles:@[@"确定", @"取消"]
                                                                        handler:handler];
    [self presentViewController:controller animated:YES completion:nil];
}

@end
